﻿using System;
using System.Collections.Generic;
using System.Text;

namespace Infrastructure
{
    public static class DateTimeUtil
    {
        /// <summary>
        /// 年月日组合成符合条件的日期
        /// </summary>
        public static string FormatDate(int year, int month, int day)
        {
            var date = DateTime.MinValue;
            try
            {
                date = DateTime.Parse($"{year}-{month}-{day}");
            }
            catch
            {
                try
                {
                    date = DateTime.Parse($"{year}-{month}-{day - 1}");
                }
                catch
                {
                    try
                    {
                        date = DateTime.Parse($"{year}-{month}-{day - 2}");
                    }
                    catch
                    {
                        try
                        {
                            date = DateTime.Parse($"{year}-{month}-{day - 3}");
                        }
                        catch
                        {
                            // ignored
                        }
                    }
                }
            }
            return date.ToString("yyyy-MM-dd");
        }

        public static DateTime ToDateTime(this string time)
        {
            var date = DateTime.MinValue;
            try
            {
                date = DateTime.Parse(time);
            }
            catch
            {
            }
            return date;
        }
    }
}
